(function(){

function compairPoint2(a, b){
	return a[0] == b[0] && a[1] == b[1];
}

function compairPoint(a, b){
	if(compairPoint2(a, b)) return true;

	var A = a.slice(2);
	A.unshift([a[0], a[1]]);
	var B = b.slice(2);
	B.unshift([b[0], b[1]]);


	return A.some(function(_a){
		return B.some(function(_b){
			return compairPoint2(_a, _b);
		})
	})

}

function CreatePainterObject(q, mosaicSize, debug){

	var painter = new CanvasPainter(q);
	painter.debug = !!debug;
	painter.mosaicSize = mosaicSize || 24;

	painter.onbegin = function(point, state){
		var _ = this;
		_.ctx
			.clearRect(0, 0, _.cvs.width, _.cvs.height);
		_.path.length && _.path.splice(0, _.path.length);
		_.ctx.beginPath();
		_.ctx.moveTo(point[0], point[1]);
		_.path.push(point);

		if(_.autoStop > 0){
			_.$autoStop = setTimeout(function(){
				_.stop(_.currentPoint);
			}, _.autoStop);
		}
	};
	painter.onmove = function(point, state){
		this.ctx.lineTo(point[0], point[1]);
		this.ctx.strokeStyle = this.runtime.strokeStyle;
		this.ctx.lineWidth = this.runtime.lineWidth;
		this.ctx.stroke();
		this.ctx.moveTo(point[0], point[1]);
		this.path.push(point);
	};
	painter.onstop = function(point, state){

		// var cdata = CanvasPainter.getImageMosaicData(this.ctx, this.mosaicSize, 0);
		// var sdata = this.getTargetData(0);

		// var ext = Math.abs(sdata.length - cdata.length);
		// var len = Math.max(cdata.length, sdata.length);
		// var bingo = 0, ng = 0;
		// cdata.forEach(function(a){
		// 	if(sdata.some(function(b){
		// 		return b[0] === a[0] && b[1] === a[1];
		// 	})){
		// 		bingo += 1;
		// 	} else {
		// 		ng += 1;
		// 	}
		// });

		// if(bingo < 0) bingo = 0;

		// var score = bingo / (len + ng);
		// score = Math.sin(score * Math.PI * .5);
		// score = Math.round(score * 10000) / 100;

		// if(typeof(this.ondraw) == 'function'){
		// 	this.ondraw(score, this.path);
		// }
		// if(this.debug){
		// 	var ctx = this.ctx;
		// 	var tar = this.target.getContext('2d');
			
		// 	ctx.save();
		// 	CanvasPainter.drawImageMosaic(
		// 		ctx, this.mosaicSize, 'rgba(255,0,0,0.5)', null, 0, 0
		// 		);
		// 	ctx.restore();

		// 	// ctx.save();
		// 	// CanvasPainter.drawImageMosaic(
		// 	// 	tar, this.mosaicSize, 'rgba(0,0,255,0.5)', ctx, 0, 2
		// 	// 	);
		// 	// ctx.restore();
		// }
	};

	return painter;
}

function CreatePainterHandle(q, conf){
	var painter = null;
	var conf = conf || {};
	var r = {
		init: function(){
			painter = CreatePainterObject(q);
			painter.debug = !!conf.debug;
			painter.mosaicSize = conf.mosaicSize || painter.mosaicSize;
			painter.autoStop = conf.autoStop || painter.autoStop;
			if(typeof(r.initImage) == 'function'){
				r.initImage(painter.target);
			}
			painter.ondraw = function(score, path){
				if(typeof(r.ondraw) == 'function'){
					r.ondraw(score, path);
				}
			};
		}
	};
	return r;
}

window.CreatePainterHandle = CreatePainterHandle;

})();